<template>
  <ArtBasicBanner class="banner" height="13.3rem" :title="`账户信息`" backgroundColor="var(--el-color-primary-light-9)"
    titleColor="var(--art-gray-900)" :decoration="false" :meteorConfig="{
      enabled: true,
      count: 10
    }" :buttonConfig="{
      show: false,
      text: ''
    }" :imageConfig="{
      src: bannerCover,
      width: '18rem',
      bottom: '-7.5rem'
    }" @click="handleBannerClick">
    <div class="banner-slot">
      <div class="item" style="display: flex;align-items: center;">
        <div>
          <p class="title">
            <span class="currency">¥</span>
            <!-- <ArtCountTo class="number box-title" :target="withdrawableData.withdrawableBalance" :duration="1500"
              separator="," /> -->
            <span class="number box-title">
              {{ withdrawableData.withdrawableBalance }}
            </span>
          </p>
          <p class="subtitle">可提现余额</p>
        </div>
        <el-button type="primary" class="withdrawButton" v-ripple @click="openDialog">
          提现
        </el-button>
      </div>
      <div class="item">
        <p class="title">
          <span class="currency">¥</span>
          <!-- <ArtCountTo class="number box-title" :target="withdrawableData.pendingAccountAmount" :duration="1500"
            separator="," /> -->
          <span class="number box-title">
            {{ withdrawableData.pendingAccountAmount }}
          </span>
        </p>
        <p class="subtitle">待入账金额</p>
      </div>
    </div>
  </ArtBasicBanner>
  <el-dialog title="提现信息" width="25%" v-model="withdrawDialog" @close="close">
    <el-form ref="withdrawFormRef" :model="withdrawForm" label-width="auto" :rules="rules">
      <el-form-item label="可提现余额：" prop="withdrawableBalance">
        <el-input v-model="withdrawableData.withdrawableBalance" class="w300" disabled></el-input>
      </el-form-item>
      <el-form-item label="提现金额：" prop="price">
        <div>
          <el-input v-model="withdrawForm.price" class="w300"></el-input>
          <div class="rate">手续费：每笔抽取费率{{ extractionRate + '%' }}，最低手续费：{{ minRate }}元，最高手续费：{{ maxRate }}元</div>
        </div>
      </el-form-item>
      <el-form-item label="提现方式：" prop="type">
        <el-select clearable v-model="withdrawForm.type" :placeholder="options.length ? '请选择提现方式' : '请添加提现设置'"
          class="w300">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号：" prop="phone">
        <el-input v-model="withdrawForm.phone" class="w300" disabled></el-input>
        <el-button class="Code" :disabled="codeCountdown > 0" @click="sendPhoneCode">
          <span v-if="codeCountdown === 0">发送验证码</span>
          <span v-else>{{ codeCountdown }}s后重新发送</span>
        </el-button>
      </el-form-item>
      <el-form-item label="验证码：" prop="code">
        <el-input v-model="withdrawForm.code" class="w300"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="withdrawDialog = false">取 消</el-button>
        <el-button type="primary" @click="submit(withdrawFormRef)">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import bannerCover from '@imgs/login/lf_icon2.webp'
import { useUserStore } from '@/store/modules/user'
import type { FormInstance, FormRules } from 'element-plus'
import { homePageInfo, sendCode, getWithdrawalMethod, withdrawOperation, basicConfiguration } from '@/api/agent'
import { ref, reactive, onMounted, computed, defineEmits } from 'vue'

const emit = defineEmits(['withdraw-success'])

const withdrawDialog = ref(false)
const withdrawFormRef = ref<FormInstance>()
const userStore = useUserStore()

const withdrawForm = reactive<any>({
  price: '',
  type: '',
  phone: userStore.getUserInfo.phone,
  code: ''
})

const withdrawableData = ref({
  withdrawableBalance: 0,
  pendingAccountAmount: 0
})

const rules = reactive<FormRules>({
  price: [
    { required: true, message: '请输入提现金额', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        const num = parseFloat(value);
        if (!value || isNaN(num)) {
          callback(new Error('请输入合法的金额'));
        } else if (num < minWithdrawalAmount.value) {
          callback(new Error(`提现金额必须大于等于${minWithdrawalAmount.value}`));
        } else if (num > withdrawableData.value.withdrawableBalance) {
          callback(new Error('提现金额不能大于可提现余额'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  type: [
    { required: true, message: '请选择提现方式', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: Function) => {
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!value) {
          callback(new Error('请输入手机号'));
        } else if (!phoneRegex.test(value)) {
          callback(new Error('请输入正确的手机号'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
})

const options = ref<any>([])

// 依赖 element-plus 和用户信息，需要实现发送验证码 API
import { ElMessage } from 'element-plus'

const codeCountdown = ref(0)
let timer: any = null

const sendPhoneCode = async () => {
  if (!withdrawForm.phone) {
    ElMessage.warning('请输入手机号码');
    return;
  }

  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(withdrawForm.phone)) {
    ElMessage.warning('请输入正确的手机号');
    return;
  }

  try {
    const res = await sendCode({
      mobile: withdrawForm.phone
    });

    if (res.code === '0') {
      ElMessage.success('验证码已发送');
      codeCountdown.value = 60;
      if (timer) clearInterval(timer);
      timer = setInterval(() => {
        codeCountdown.value--;
        if (codeCountdown.value <= 0) {
          clearInterval(timer);
          timer = null;
        }
      }, 1000);
    } else {
      ElMessage.error(res.msg || '验证码发送失败');
    }
  } catch (err) {
    ElMessage.error('验证码发送失败');
  }
}

const userInfo = computed(() => userStore.getUserInfo)

const handleBannerClick = (): void => {
  // TODO: 添加横幅点击处理逻辑
}

const getHomePageData = async () => {
  const res = await homePageInfo()
  if (res.code === '0') {
    withdrawableData.value.withdrawableBalance = Number((res.data.balance / 100).toFixed(2))
    withdrawableData.value.pendingAccountAmount = Number((res.data.unsettledIncome / 100).toFixed(2))
  }
}

const openDialog = () => {
  withdrawDialog.value = true
  getWithdrawalType()
}

const getWithdrawalType = async () => {
  const res = await getWithdrawalMethod()
  if (res.code === '0') {
    options.value = res.data.map((e: any) => {
      return {
        value: e.bankType,
        label: e.bankType === '01' ? '微信' : e.bankType === '02' ? '支付宝' : '银行卡'
      }
    })
  }
}

const submit = async (formEl: FormInstance | undefined) => {
  // try {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        const res = await withdrawOperation({
          amount: withdrawForm.price * 100,
          withdrawalType: withdrawForm.type,
          mobile: withdrawForm.phone,
          code: withdrawForm.code
        })
        if (res.code === '0') {
          ElMessage.success('提现成功')
          emit('withdraw-success')
          getHomePageData()
          withdrawDialog.value = false
        } else {
          console.log(123);
          
          ElMessage.error(res.msg)
        }
      }
    })
  // } catch (e) {
  //   console.log(e, "e==");
  // }
}

const extractionRate = ref(0)
const minWithdrawalAmount = ref(0)
const minRate = ref(0)
const maxRate = ref(0)
const getConfigData = async () => {
  const res = await basicConfiguration()
  if (res.code === '0') {
    extractionRate.value = res.data.withdrawFeePercent / 100
    minWithdrawalAmount.value = res.data.withdrawMinPrice / 100
    minRate.value = res.data.withdrawMinFee / 100
    maxRate.value = res.data.withdrawMaxFee / 100
  }
}

const close = () => {
  withdrawForm.price = ''
  withdrawForm.type = ''
  // withdrawForm.phone = ''
  withdrawForm.code = ''
}

onMounted(() => {
  getHomePageData()
  getConfigData()
})
</script>
<style lang="scss" scoped>
.banner {
  justify-content: center;

  .banner-slot {
    display: flex;
    margin-top: 24px;

    .item {
      margin-right: 30px;

      &:first-of-type {
        padding-right: 50px;
        border-right: 1px solid var(--art-gray-300);
      }

      .title {
        font-size: 30px;
        color: var(--art-gray-900) !important;

        .currency {
          margin-right: 6px;
          font-size: 16px;
          vertical-align: baseline;
        }

        i {
          position: relative;
          top: -10px;
          margin-left: 10px;
          font-size: 16px;
        }
      }

      .subtitle {
        margin-top: 20px;
        font-size: 14px;
        color: var(--art-gray-700) !important;
      }
    }
  }

}

.withdrawButton {
  margin-left: 50px;
}

.w300 {
  width: 300px;
}

.Code {
  margin-left: 10px;
  width: 120px;
}

.rate {
  font-size: 12px;
}
</style>
